package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entites.JsonResult;
import com.atguigu.springcloud.entites.Payment;
import com.atguigu.springcloud.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName PaymentController
 * @Author VCR
 * @Date 2021/12/20 21:09
 * @Version 1.0
 */
@RestController
@RequestMapping("payment")
@Slf4j
public class PaymentController {

    @Autowired
    private IPaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("create")
    public JsonResult create(@RequestBody Payment payment) {
        int insert = paymentService.insert(payment);
        System.out.println(insert);
        System.out.println("999999");
        return new JsonResult(200, "insert success,serverPort:" + serverPort, insert);
    }

    @GetMapping("/get/{id}")
    public JsonResult queryPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.queryPaymentById(id);
        System.out.println("324242");
        if (payment != null) {
            return new JsonResult(200, "insert success,serverPort:" + serverPort, payment);
        } else {
            return JsonResult.defaultError();
        }
    }

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            log.info("***** element:"+element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/feign/timeout")
    public String paymentFeignTimeout(){
        // 模拟业务处理需要3秒(超时测试)
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }


}
